package middleware

import (
	"gitee.com/war2001/NiuMaEasyGo/global"
	"gitee.com/war2001/NiuMaEasyGo/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// AuthMiddleware 认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 实现认证逻辑
		c.Next()
	}
}

// PermissionMiddleware 权限中间件
func PermissionMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 实现权限验证逻辑
		c.Next()
	}
}

// LoginLogMiddleware 登录日志中间件
func LoginLogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 先执行后续中间件和处理函数
		c.Next()

		// 获取登录结果
		if c.Writer.Status() == 200 && c.FullPath() == "/api/v1/auth/login" {
			// 获取用户信息
			userID, exists := c.Get("user_id")
			if !exists {
				return
			}
			username, exists := c.Get("username")
			if !exists {
				return
			}

			// 记录登录日志
			if global.Services != nil {
				if services, ok := global.Services.(*service.Services); ok && services.LoginLog != nil {
					err := services.LoginLog.RecordLoginLog(
						userID.(uint),
						username.(string),
						"账号密码",
						c.ClientIP(),
						c.Request.UserAgent(),
						1, // 登录成功
						"登录成功",
					)
					if err != nil {
						// 只记录错误，不影响正常流程
						zap.L().Error("记录登录日志失败", zap.Error(err))
					}
				}
			}
		} else if c.Writer.Status() != 200 && c.FullPath() == "/api/v1/auth/login" {
			// 登录失败，尝试从请求中获取用户名
			username := c.PostForm("username")
			if username == "" {
				// 尝试从JSON中获取
				var loginData struct {
					Username string `json:"username"`
				}
				if err := c.ShouldBindJSON(&loginData); err == nil {
					username = loginData.Username
				}
			}

			// 记录登录失败日志
			if global.Services != nil && username != "" {
				if services, ok := global.Services.(*service.Services); ok && services.LoginLog != nil {
					err := services.LoginLog.RecordLoginLog(
						0, // 未登录成功，无用户ID
						username,
						"账号密码",
						c.ClientIP(),
						c.Request.UserAgent(),
						0, // 登录失败
						"登录失败: "+c.Errors.String(),
					)
					if err != nil {
						// 只记录错误，不影响正常流程
						zap.L().Error("记录登录失败日志失败", zap.Error(err))
					}
				}
			}
		}
	}
}
